#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
初始化部门数据脚本
将前端Departments.vue中的模拟数据添加到数据库
"""

import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from sqlalchemy import create_engine, Column, Integer, String, DateTime, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from datetime import datetime
import logging

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

# 数据库连接配置
DATABASE_URL = "sqlite:///./pilot_manage.db"
engine = create_engine(DATABASE_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()

# 定义Department模型
class Department(Base):
    __tablename__ = "departments"
    
    id = Column(Integer, primary_key=True, index=True)
    name = Column(String(100), unique=True, index=True, nullable=False)
    description = Column(String(255))
    parent_id = Column(Integer, ForeignKey('departments.id'))
    created_at = Column(DateTime, default=datetime.now)
    updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now)

def init_departments():
    """初始化部门数据"""
    # 创建数据库会话
    db = SessionLocal()
    
    try:
        # 检查是否已有部门数据
        existing_departments = db.query(Department).count()
        if existing_departments > 0:
            logger.info(f"数据库中已有 {existing_departments} 个部门数据，跳过初始化")
            print(f"数据库中已有 {existing_departments} 个部门数据，跳过初始化")
            return
        
        # 前端模拟的部门数据
        departments_data = [
            {
                'name': '技术部',
                'leader': '张三',  # 注意：模型中没有leader字段，会被忽略
                'phone': '13800138001',  # 注意：模型中没有phone字段，会被忽略
                'description': '负责无人机技术研发和维护',
                'created_at': datetime.strptime('2024-01-01 00:00:00', '%Y-%m-%d %H:%M:%S')
            },
            {
                'name': '运营部',
                'leader': '李四',
                'phone': '13800138002',
                'description': '负责无人机日常运营和飞行任务',
                'created_at': datetime.strptime('2024-01-02 10:00:00', '%Y-%m-%d %H:%M:%S')
            },
            {
                'name': '研发部',
                'leader': '王五',
                'phone': '13800138003',
                'description': '负责新产品研发和测试',
                'created_at': datetime.strptime('2024-01-03 14:00:00', '%Y-%m-%d %H:%M:%S')
            },
            {
                'name': '市场部',
                'leader': '赵六',
                'phone': '13800138004',
                'description': '负责市场推广和客户服务',
                'created_at': datetime.strptime('2024-01-04 09:00:00', '%Y-%m-%d %H:%M:%S')
            },
            {
                'name': '安全部',
                'leader': '钱七',
                'phone': '13800138005',
                'description': '负责飞行安全监督和管理',
                'created_at': datetime.strptime('2024-01-05 16:00:00', '%Y-%m-%d %H:%M:%S')
            }
        ]
        
        # 插入部门数据
        for dept_data in departments_data:
            # 过滤掉模型中不存在的字段
            valid_data = {
                'name': dept_data['name'],
                'description': dept_data['description'],
                'created_at': dept_data['created_at']
            }
            
            department = Department(**valid_data)
            db.add(department)
        
        db.commit()
        logger.info(f"成功初始化 {len(departments_data)} 个部门数据")
        print(f"成功初始化 {len(departments_data)} 个部门数据到数据库")
        
    except Exception as e:
        logger.error(f"初始化部门数据时出错: {str(e)}")
        print(f"错误：初始化部门数据失败: {str(e)}")
        db.rollback()
    finally:
        db.close()

if __name__ == "__main__":
    print("开始初始化部门数据...")
    init_departments()
    print("操作完成")